<template>
  <el-dialog
    class="public-dialog"
    :title="disabled ? '订单详情' : isEdit ? '修改退款单' : '新增退款单'"
    width="1000"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    :close-on-click-modal="false"
  >
    <div v-if="!disabled">
      <FormTitle title="订单信息" />
      <div class="w-[300px]">
        <FormCombinedNorm v-model="noCombined" :options="orderNoOptions" :itemProps="{ onChange: handleChange, disabled: !!props.id }" :style="{ width: '400px' }">
          <template #default>
            <el-input v-model.trim="noCombined.value" @blur="handleBlur" clearable :disabled="!!props.id" placeholder="请输入" />
          </template>
        </FormCombinedNorm>
      </div>
      <div class="flex flex-wrap order-info">
        <Descriptions
          label-width="100px"
          v-for="item in orderInfo"
          :key="item.label"
          :label="item.label"
          :value="item.currency ? (orderData?.[item.field] || '0') + ' ' + (orderData.original_order_currency || '') : orderData?.[item.field] || '-'"
        />
      </div>
      <!-- 退款信息 -->
      <RefundInfo ref="infoRef" :info="orderData" :disabled="disabled" :isEdit="isEdit" />
      <RefundProduct ref="productRef" :data="orderData?.items" :disabled="disabled" @updateAmount="updateAmount" />
      <!-- 退款描述 -->
      <RefundDesc ref="descRef" :info="orderData" :disabled="disabled" />
    </div>
    <div v-else>
      <LookDtl :info="orderData" />
    </div>
    <template #footer>
      <el-button :disabled="loading" @click="handleClose(false)">
        {{ disabled ? "关闭" : "取消" }}
      </el-button>
      <el-button v-if="!disabled" type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus"
import { overallOptions } from "@/api/public"
import FormTitle from "@/components/XForm/FormTitle.vue"
import FormCombinedNorm from "@/components/XForm/FormCombinedNorm.vue"
import Descriptions from "@/components/Descriptions/index.vue"
import RefundInfo from "./components/RefundInfo/index.vue"
import RefundProduct from "./components/RefundProduct/index.vue"
import RefundDesc from "./components/RefundDesc/index.vue"
import LookDtl from "./components/lookDtl.vue"
import { getRefundOverflow, createRefund, refundDetail, updateRefund } from "../../api/index"
import { computed, nextTick } from "vue"

const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})
const updateAmount = (v) => {
  orderData.value.refund_amount = v
}

const emit = defineEmits(["update:modelValue", "refresh", "close"])
const noCombined = ref({ type: "order_sn", value: "" })
const orderNoOptions = [
  { label: "系统订单号", value: "order_sn" },
  { label: "平台订单号", value: "platform_order_sn" },
]
const orderInfo = [
  { label: "平台/站点", field: "platformAll" },
  { label: "店铺", field: "shop" },
  { label: "下单时间", field: "order_time" },
  // { label: "订单来源", field: "build_order_type" },
  { label: "订单来源", field: "build_order_type_desc" },

  { label: "订单类型", field: "order_type_desc" },
  { label: "发货状态", field: "shipping_status_desc" },
  // { label: "订单金额", field: "order_amount", currency: true },
  { label: "订单金额", field: "original_order_amount", currency: true },
  { label: "已退金额", field: "refund_amount_show", currency: true },
  { label: "剩余退款金额", field: "refundable_amount_tax_show", currency: true, labelWidth: "200px" },
]

const infoRef = ref()
const productRef = ref()
const descRef = ref()

const loading = ref()
const orderData = ref({
  refund_channel: 1,
  is_generate_return: 1, // 自动生成退件单 提交时注意判断
  tax_included: true,
  // is_api_refund:1
})

watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)

const getDetail = async (id) => {
  try {
    const { data } = await refundDetail({ id })
    orderData.value = {
      handleType: "updata",
      ...data,
      items: data?.products?.map((n) => {
        let _count = (n.orderQuantity || 0) - (n.totalRefundQuantity || 0) || 0
        _count = _count < 0 ? 0 : _count
        return {
          ...n,
          quantity: n.orderQuantity,
          count: n.quantity,
          refund_quantity: n.totalRefundQuantity,
          id: n.order_item_id,
        }
      }),
      platformAll: `${data.platform}${data.site ? `/${data.site}` : ""}`,

      // 初始化数据  后端默认返回0 待优化
      refund_method: data?.refund_method || "",
      platform_refund_reason: data?.platform_refund_reason || "",
      // 已退金额
      refund_amount_show: data?.refund_amount_tax,

      // 订单信息
      order_type_desc: data?.shipping_type_desc,
      order_amount: data?.original_order_amount,
      order_time: data?.create_time,

      original_order_currency: data?.order_currency,

      // 退款金额 新增编辑数据差异化赋值
      refund_amount: data.tax_included ? data?.refund_amount_tax : data?.refund_amount,
      refundable_amount: data?.refund_amount,
      refundable_amount_tax: data?.refund_amount_tax,
      // 剩余退款金额 单展示
      refundable_amount_tax_show: data.refundable_amount_tax,
    }
    noCombined.value = { type: "order_sn", value: data?.order_sn }
    // console.log(orderData.value)
  } catch (e) {
    orderData.value = {}
    console.error(e)
  }
}

const handleChange = (e) => {
  nextTick(() => {
    handleBlur()
  })
}
const handleBlur = () => {
  const _val = noCombined.value.value
  if (_val && _val?.length) {
    handleGetOrderInfo()
    return
  }
  orderData.value = {}
}
const handleGetOrderInfo = async () => {
  try {
    const _val = noCombined.value
    const { data } = await getRefundOverflow({ [_val?.type]: _val?.value })
    // console.log(data);
    const { order, payment, logistics } = data

    orderData.value = {
      exists_api_refund: data.exists_api_refund,
      ...logistics,
      ...order,
      items: order?.items?.map((n) => {
        let _count = (n.quantity || 0) - (n.refund_quantity || 0) || 0
        _count = _count < 0 ? 0 : _count
        return {
          ...n,
          count: _count,
          max: _count,
        }
      }),
      platformAll: `${order.platform}${order.site ? `/${order.site}` : ""}`,
      refund_amount: data?.refund_amount,
      refund_amount: data?.refundable_amount,
      // refund_amount: data?.original_order_amount,

      tax_included: true,
      refund_amount: data?.refundable_amount_tax,

      refundable_amount: data?.refundable_amount,
      refundable_amount_tax: data?.refundable_amount_tax,
      // refundable_amount_tax: data?.payment?.refund_amount_tax,
      is_dispute: 0,
      // 初始化  退款渠道 退款方式 收款人 收款账户
      refund_channel: payment?.payment_type || 1,
      refund_method: payment?.payment_mode || "",
      // payee: order?.recipient?.buyer_name,
      accounts_receivable: order?.recipient.recipient_email,

      // 订单信息
      order_type_desc: order?.shipping_type_desc,

      // 已退金额 单展示
      refund_amount_show: data?.refund_amount_tax,
      // 剩余退款金额 单展示
      refundable_amount_tax_show: data.refundable_amount_tax,
    }
    // // otto 默认 退件追踪号
    if (order.platform_id == 3) {
      // orderData.value.tracking_number = logistics?.return_number
      //  是否api退款
      orderData.value.is_api_refund = 0
    } else {
      orderData.value.is_api_refund = ""
    }

    // // walmart订单 默认 收款人
    // if (order.platform_id == 4) {
    orderData.value.payee = `${order?.recipient?.recipient_name} ${order?.recipient?.recipient_last_name}`
    // }

    // {payment_mode
    //   field: 'refund_method',

    // accounts_receivable
    // recipient.recipient_email
  } catch (e) {
    orderData.value = {}
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.id
})
const handleSave = async () => {
  console.log(orderData.value)
  const save = async () => {
    await infoRef.value.form.submit()
    await descRef.value.form.submit()
    loading.value = true
    const refundInfo = { ...orderData.value }
    refundInfo.products = refundInfo.items?.map((n) => ({ quantity: n.count, item_id: n.id }))
    delete refundInfo.items

    // 待优化  未选择不传值
    if (refundInfo.return_warehouse_id) {
      let return_warehouse = descRef.value.warehouseOpt.find((v) => v.value == refundInfo.return_warehouse_id)?.label || ""
      refundInfo.return_warehouse_id = Number(refundInfo.return_warehouse_id)
      refundInfo.return_warehouse = return_warehouse
    } else {
      delete refundInfo.return_warehouse_id
      delete refundInfo.return_warehouse
    }
    // 去空格 空字段
    for (const key in refundInfo) {
      if (!refundInfo[key] && refundInfo[key] != 0) {
        delete refundInfo[key]
      } else {
        typeof refundInfo[key] == "string" && (refundInfo[key] = refundInfo[key].trim())
      }
    }
    // 含税 不含税
    refundInfo.refund_amount = Number(refundInfo.refund_amount)
    refundInfo.tax_included = !!refundInfo.tax_included
    if (refundInfo.tax_included) {
      refundInfo.refund_amount_tax = refundInfo.refund_amount
      // refundInfo.refund_amount = 0
    }

    // console.log("refundInfo")
    // console.log(refundInfo)
    if (refundInfo.refund_amount == 0 || !refundInfo.refund_amount) {
      ElMessage.warning("退款金额不能为0")
      loading.value = false
      return
    }

    const { id } = props
    const api = {
      edit: updateRefund,
      add: createRefund,
    }
    let params = {
      id: id || undefined,
      order_sn: orderData.value?.order_sn,
      ...refundInfo,
      is_api_refund: orderData.value?.is_api_refund,
    }
    if (params.cargo_handler == 1) {
      delete params.is_generate_return
    }

    // return
    await api[isEdit.value ? "edit" : "add"](params)
    ElMessage.success(isEdit.value ? "修改成功" : "保存成功")
    loading.value = false
    handleClose(true)
  }

  // return 1241218840030001
  try {
    if (!orderData.value?.order_sn) {
      ElMessage.warning("请先输入订单编号")
      return
    }
    
    if (orderData.value.exists_api_refund == 1 && orderData.value.platform_id == 1 && orderData.value.is_api_refund == 1) {
      // save()
      await ElMessageBox.confirm("该订单已操作过API退款，是否确认再次退款？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          save()
        })
        .catch(() => {})
    } else {
      save()
    }
    // save()
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息")
    }
    console.error(e)
    loading.value = false
  } finally {
    loading.value = false
  }
}

const handleClose = (refresh) => {
  orderData.value = {}
  loading.value = false
  noCombined.value = { type: "order_sn" }
  emit("update:modelValue", false)
  emit("close")
  if (refresh) emit("refresh")
}

defineExpose({
  noCombined,
  handleGetOrderInfo,
  handleChange,
})
</script>
<style lang="scss" scoped>
.order-info {
  // background: #f6faff;
  background: var(--base-table-header-bg-color);
  // background: #000;
  padding: 4px 16px;
  margin-top: 8px;
  :deep(.descriptions .value) {
    min-width: 200px;
  }
}
:deep(.form-title) {
  margin-bottom: 8px;
}
:deep(.descriptions) {
  margin: 9px 0;
}
</style>
